﻿using MyWeb.Repository.UnitOfWorks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using MyWeb.Model.Models;
using MyWeb.Model;
using MyWeb.Common.Helper;
using MyWeb.Business.Base;
using MyWeb.Model.User;
using MyWeb.Services;
using MyWeb.Model.Dto;

namespace MyWeb.Business.System.Impl
{
    public class DepartmentService: BaseBusiness<Department>, IDepartmentService
    {
        private readonly SqlSugarScope scope;
        private readonly IOperatorProvider _provider;
        public DepartmentService(IUnitOfWorkManage unitOfWorkManage,IOperatorProvider provider)
        {
            scope = unitOfWorkManage.GetDbClient();
            _provider = provider;
        }

        public async Task<bool> AddInfo(Department department)
        {
            department.CreateTime = DateTime.Now;
            department.CreateBy = _provider.GetUserInfo().Name;
            _ = await scope.Insertable(department).ExecuteReturnSnowflakeIdAsync();
            return true;
        }

        public async Task<bool> EditInfo(DepartmentDto dto)
        {
            var entity = await scope.Queryable<Department>().Where(a => a.Id == dto.Id).FirstAsync();
            if (entity == null)
            {
                throw new Exception("部门不存在！！");
            }
            entity.Name = dto.Name;
            entity.Status = dto.Status;
            entity.Leader = dto.Leader;
            entity.OrderSort = dto.OrderSort;
            entity.ModifyTime = DateTime.Now;
            entity.ModifyBy = _provider.GetUserInfo().Name;
            var exe = await scope.Updateable(entity)
                .UpdateColumns(s => new { s.Name, s.Status, s.Leader, s.OrderSort,s.ModifyBy,s.ModifyTime })
                .ExecuteCommandAsync();
            return exe > 0 ? true : false;
        }

        public async Task<PageModel<DepartmentDto>> GetDepartment(DepartmentDto dto)
        {
            var userinfo = _provider.GetUserInfo();

            var linq = scope.Queryable<Department>()
                .Where(a => a.IsDeleted == false)
                .WhereIF(!string.IsNullOrEmpty(dto.Key), d => d.Name.Contains(dto.Key))
                .Select(a => new DepartmentDto
                {
                    Id = a.Id,
                    Pid = a.Pid,
                    //PidArr
                    CodeRelationship = a.CodeRelationship,
                    Name = a.Name,
                    Leader = a.Leader,
                    OrderSort = a.OrderSort,
                    IsDeleted = a.IsDeleted,
                    CreateBy = a.CreateBy,
                    CreateTime = a.CreateTime,
                    ModifyBy = a.ModifyBy,
                    ModifyTime = a.ModifyTime,
                    //hasChildren
                });

            var departs = await linq.ToListAsync();
            var data = await linq.WhereIF(dto.Pid > 0, a => a.Pid == dto.Pid)
                .Skip((dto.Pagination.PageIndex - 1) * dto.Pagination.PageSize)
                .Take(dto.Pagination.PageSize)
                .ToListAsync();
            var count = await linq.WhereIF(dto.Pid > 0, a => a.Pid == dto.Pid).CountAsync();

            foreach (var item in data)
            {
                item.hasChildren = departs.Where(d => d.Pid == item.Id).Any();

                List<long> prents = new List<long>();
                var prent = departs.FirstOrDefault(d => d.Id == item.Pid);
                while (prent != null)
                {
                    prents.Add(prent.Id);
                    prent = departs.FirstOrDefault(d => d.Id == prent.Pid);
                }
                prents.Insert(0, 0);
                item.PidArr = prents;
            }

            return new PageModel<DepartmentDto>(dto.Pagination.PageIndex, count, dto.Pagination.PageSize, data);
        }
        /// <summary>
        /// 获取部门数
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public async Task<DepartmentTree> GetDepartmentTree(long pid = 0)
        {
            var departmentTrees = await scope.Queryable<Department>()
                .Where(d => d.IsDeleted == false)
                .Select(d => new DepartmentTree()
                {
                    id = d.Id,
                    label = d.Name,
                    pid = d.Pid,
                    order = d.OrderSort,
                }).OrderBy(d => d.order).ToListAsync();

            DepartmentTree rootRoot = new DepartmentTree
            {
                id = 0,
                pid = 0,
                label = "根节点"
            };

            RecursionHelper<DepartmentTree>.LoopToAppendChildren(departmentTrees, rootRoot, pid);

            return rootRoot;
        }

        public async Task<object> Remove(long uid)
        {
            var entity = await scope.Queryable<Department>().Where(u => u.Id == uid && u.IsDeleted == false).FirstAsync();
            if (entity != null)
            {
                await scope.Updateable<Department>().SetColumns(u => u.IsDeleted == true).Where(u => u.Id == entity.Id).ExecuteCommandAsync();

                return "删除成功";
            }
            else
            {
                return "用户Id不存在！";
            }
        }
    }
}
